package com.speech.net;

import android.content.Context;

import com.speech.AppConfig;
import com.speech.activity.RegisterActivity;
import com.speech.net.constant.EnumReqestActionCode;
import com.speech.net.entity.MessageC2S;
import com.speech.net.entity.MessageC2SBuilder;
import com.speech.net.entity.MessageS2C;
import com.speech.net.service.HttpCommunicationService;
import com.speech.utils.AESEncryption;
import com.speech.utils.JsonProcessor;

import java.util.concurrent.TimeUnit;

import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

public class HttpCommunicationManager {

    private final static int OKHTTP_CONNECT_TIME_OUT = 30;//15s
    private final static int OKHTTP_READ_TIME_OUT = 30;//20s
    private final static int OKHTTP_WRITE_TIME_OUT = 30;//20s

    private static HttpCommunicationManager mHttpCommunicationManager;

    private OkHttpClient mOkHttpClient;

    private Retrofit mRetrofit;

    private HttpCommunicationManager() {
        _init();
    }

    private void _init() {
        if (mRetrofit == null || mOkHttpClient == null) {
            HttpLoggingInterceptor LoginInterceptor = new HttpLoggingInterceptor();
            LoginInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.addInterceptor(LoginInterceptor);
            builder.connectTimeout(OKHTTP_CONNECT_TIME_OUT, TimeUnit.SECONDS);
            builder.readTimeout(OKHTTP_READ_TIME_OUT, TimeUnit.SECONDS);
            builder.writeTimeout(OKHTTP_WRITE_TIME_OUT, TimeUnit.SECONDS);
            mOkHttpClient = builder.build();

            mRetrofit = new Retrofit.Builder()
                    .baseUrl(AppConfig.SERVER_BASE_URL)
                    .addConverterFactory(JacksonConverterFactory.create())
                    .client(mOkHttpClient)
                    .build();
        }
    }

    public static HttpCommunicationManager getInstance() {
        if (mHttpCommunicationManager == null) {
            mHttpCommunicationManager = new HttpCommunicationManager();
        }
        return mHttpCommunicationManager;
    }

    /**
     * 执行post请求
     *
     * @param json  必须是加密前的
     * @param callback
     */
    public void doPost(String json, Callback<ResponseBody> callback) {
        String json_encode = AESEncryption.encrypt(json);
        json_encode = json_encode.replace("+","(").replace("/",")").replace("=","@");

        HttpCommunicationService service = mRetrofit.create(HttpCommunicationService.class);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), json_encode);
        Call<ResponseBody> call = service.doPost(requestBody);

        call.enqueue(callback);
    }

    public void doSignInDevice(final Context context, final String strOriginRequestJson, final BasicCallBack originCallBack) {
        MessageC2S msg = MessageC2SBuilder.buildGeneral_MessageC2S(context, EnumReqestActionCode.设备登记, null);

        String json = JsonProcessor.StcGetJson(msg);

        doPost(json, new BasicCallBack(context, strOriginRequestJson, new BasicCallBack.BasicCallBackListener() {
            @Override
            public void success(MessageS2C msg_s2c) {
                doPost(strOriginRequestJson, originCallBack);
            }

            @Override
            public void fail(MessageS2C msg_s2c) {
                new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText(msg_s2c.strMsgUI)
                        .setConfirmText("OK")
                        .show();
            }
        }));
    }

    public void doTokenLogin(final Context context, final String strOriginRequestJson, final BasicCallBack originCallBack){
        MessageC2S msg = MessageC2SBuilder.buildGeneral_MessageC2S(context, EnumReqestActionCode.token登录, null);

        String json = JsonProcessor.StcGetJson(msg);

        doPost(json, new BasicCallBack(context, strOriginRequestJson, new BasicCallBack.BasicCallBackListener() {
            @Override
            public void success(MessageS2C msg_s2c) {
                doPost(strOriginRequestJson, originCallBack);
            }

            @Override
            public void fail(MessageS2C msg_s2c) {
                new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText(msg_s2c.strMsgUI)
                        .setConfirmText("OK")
                        .show();
            }
        }));

    }
}
